/*
 * File Name��SaveBitmap.java
 * Copyright��Copyright 2008-2015 CiWong.Inc. All Rights Reserved.
 * Description�� SaveBitmap.java
 * Modify By��RES-KUNZHU
 * Modify Date��2015-6-19
 * Modify Type��Add
 */
package com.zxing.camera;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.os.Environment;
import android.util.Log;

import com.ciwong.libs.utils.CWLog;

/**
 * TODO Description of class��
 * <p>
 * TODO Detail Description
 * <p>
 * TODO Sample Code
 * 
 * <pre>
 * </pre>
 * 
 * @author RES-KUNZHU
 * @version ciwong v.1.0 2015-6-19
 * @since ciwong v.1.0
 */
public class SaveBitmap
{
    public static String save(byte[] data, Camera camera)
    {
        String fileName = "IMG_"
                + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date())
                        .toString() + ".jpg";
        File sdRoot = Environment.getExternalStorageDirectory();
        String dir = "/Camera/";
        File mkDir = new File(sdRoot, dir);
        if (!mkDir.exists())
            mkDir.mkdirs();
        File pictureFile = new File(sdRoot, dir + fileName);
        if (!pictureFile.exists())
        {
            try
            {
                pictureFile.createNewFile();
                Camera.Parameters parameters = camera.getParameters();
                Size size = parameters.getPreviewSize();
                YuvImage image = new YuvImage(data,
                        parameters.getPreviewFormat(), size.width, size.height,
                        null);

                FileOutputStream filecon = new FileOutputStream(pictureFile);
                image.compressToJpeg(
                        new Rect(0, 0, image.getWidth(), image.getHeight()),
                        90, filecon);
                filecon.close();
                return pictureFile.getAbsolutePath();
                // if (image != null) {
                // ByteArrayOutputStream stream = new ByteArrayOutputStream();
                // image.compressToJpeg(new Rect(0, 0, size.width, size.height),
                // 80, stream);
                // Bitmap bmp =
                // BitmapFactory.decodeFile(pictureFile.getAbsolutePath());
                //
                // // saveBitmap(bmp,mkDir.getAbsolutePath()+"/ttt.jpg");
                // stream.close();
                // return bmp;
                // }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 图片旋转
     * @param data
     * @param orientationDegree
     * @return
     */
    public static Bitmap adjustPhotoRotation(byte[] data, int orientationDegree)
    {
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        return adjustPhotoRotation(bitmap, orientationDegree);
    }

    public static Bitmap adjustPhotoRotation(Bitmap bm,
            final int orientationDegree)
    {
        Matrix m = new Matrix();
        m.setRotate(orientationDegree, (float) bm.getWidth() / 2,
                (float) bm.getHeight() / 2);

        try
        {
            Bitmap tempBitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                    bm.getHeight(), m, true);
            if (bm != null && !bm.isRecycled())
            {
                bm.recycle();
            }
            return tempBitmap;
        }
        catch (OutOfMemoryError ex)
        {
        }
        return null;
    }

    public static Bitmap decodeToBitMap(byte[] data, Camera mCamera)
    {
        Size size = mCamera.getParameters().getPreviewSize();
        try
        {
            YuvImage image = new YuvImage(data, ImageFormat.NV21, size.width,
                    size.height, null);
            if (image != null)
            {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                image.compressToJpeg(new Rect(0, 0, size.width, size.height),
                        80, stream);
                Bitmap bmp = BitmapFactory.decodeByteArray(
                        stream.toByteArray(), 0, stream.size());
                stream.close();
                return bmp;
            }
        }
        catch (Exception ex)
        {
            Log.e("Sys", "Error:" + ex.getMessage());
        }
        return null;
    }

    public static String saveBitmap(Bitmap bm, String path)
    {
        if (bm == null || bm.isRecycled() || path == null)
        {
            return null;
        }

        CWLog.e("DecodeHandler savebitmap", "h = " + bm.getHeight() + " w = "
                + bm.getWidth());
        String tmpPath = path.substring(0, path.lastIndexOf("/"));
        File file = new File(tmpPath);
        FileOutputStream out = null;
        if (!file.exists())
        {
            file.mkdirs();
        }

        // ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // byte[] buf = baos.toByteArray();
        // InputStream sbs = new ByteArrayInputStream(buf);
        try
        {
            out = new FileOutputStream(path);
            bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
            // out = new FileOutputStream(path);
            // out.write(buf, 0, buf.length);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            path = null;
        }
        finally
        {
            if (out != null)
            {
                try
                {
                    out.flush();
                    out.close();
                    // baos.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    path = null;
                }
            }
        }
        return path;
    }
}
